package com.hy.chat.client.presenter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.hy.chat.client.Chat;
import com.hy.chat.client.ChatServiceAsync;
import com.hy.chat.client.widget.ChatTabItem;

public class AnonymousChatPersenter implements Presenter{
	
	private Display display;
	private ChatServiceAsync greetingService= Registry.get(Chat.CHAT_SERVICE);
	private static final String  ICON = "myGwt-image1";

//	private Panel panel;
	
	public AnonymousChatPersenter(Panel panel,Display display) {
		super();
		this.display = display;
		//this.panel = panel;
		this.bind();
	}

	public AnonymousChatPersenter(Display display) {
		super();
		this.display = display;
		//this.panel = panel;
		this.bind();
	}
	public interface Display{
		public Button	getSentButton() ;
		public TabPanel	getTabPanel() ;
		public ChatTabItem	getChatTabItem() ;
		public HtmlEditor	getHtmlEditor() ;
	    public Widget asWidget();

	}
	

	@Override
	public void go(HasWidgets container) {
		container.add(display.asWidget());
	}
	
	public void bind() {
		
		this.sentMessage();
		//this.repeatSentMessage();
	}
	
	
	
	private String getCurrentDateTime() {
		return DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_SHORT).format(new Date());
	}
	
	
	private ChatTabItem createChatTabItem (String sessionId,String message,int index,boolean closable) {
		ChatTabItem chatTabItem = new ChatTabItem("与客户"+sessionId.substring(0, 6)+"会话");  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(100);  
		    chatTabItem.setIconStyle(ICON);

		    chatTabItem.setData("messageIndex", index);
		    chatTabItem.setData("sessionId", sessionId);
		    chatTabItem.setClosable(closable);
//		    chatTabItem.addText(message);  
		    chatTabItem.setScrollMode(Scroll.AUTOY); 

		    Html xx =chatTabItem.addText(message);  
		   // chatTabItem.focus();
		    return chatTabItem;
	}
	
	private void sentMessage() {
		//为按钮，用于完成：1提交和返回数据2清空文本编辑器
    	display.getSentButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				//MessageBox.alert("提示",	"发送成功！", null);

				final BaseModel indexAndMessage = new BaseModel();
				indexAndMessage.set("index", display.getChatTabItem().getData("messageIndex"));
//					String preStr = "客户说："+DateTimeFormat.getShortDateTimeFormat().toString()+"<br>";
				String preStr = "客户说："+getCurrentDateTime()+"<br>";
				indexAndMessage.set("message", preStr + display.getHtmlEditor().getValue());
				indexAndMessage.set("sessionId", display.getChatTabItem().getData("sessionId"));
				
				callChatService(indexAndMessage, display.getHtmlEditor(), display.getChatTabItem());
				
				display.getSentButton().setData("isClicked", true);
				
		    	final Timer t = new Timer() {  
			        float i;  		        
			        @Override  
			        public void run() { 
			        	final BaseModel indexAndMessageRepeat = new BaseModel();
				    	indexAndMessageRepeat.set("index", display.getChatTabItem().getData("messageIndex"));
						
						indexAndMessageRepeat.set("sessionId", display.getChatTabItem().getData("sessionId"));
						System.out.println("indexAndMessageRepeat sessionId "+ indexAndMessageRepeat.get("sessionId"));
			        	System.out.println("--------"+new Date());
						System.out.println("re indexAndMessageRepeat sessionId "+ indexAndMessageRepeat.get("sessionId")+
								"index is "+indexAndMessageRepeat.get("index"));

						callChatService(indexAndMessageRepeat,  display.getChatTabItem());
			        		        	
			        }  
			      }; 
			      
			     if (display.getSentButton().getData("isClicked")!=null&&(Boolean)display.getSentButton().getData("isClicked")==true) {
				      t.scheduleRepeating(1000);  
				}
				
				
			}
		});
	}

	
	private BaseModel encapsulateIndexAndMessage() {
		return null;
	}
	
	
	

	private void callChatService(BaseModel indexAndMessage,final ChatTabItem chatTabItem) {
		this.callChatService(indexAndMessage, null, chatTabItem);
	}
	
	private void callChatService(BaseModel indexAndMessage,final HtmlEditor htmlEditor,final ChatTabItem chatTabItem) {
		greetingService.getIndexAndMessage(indexAndMessage,  new AsyncCallback<BaseModel>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("*** "+GWT.getModuleBaseURL()+"chatService");

				MessageBox.alert("警告",	"后台的Rpc调用失败，请联系管理员或者稍后再试！", null);
			}

			@Override
			public void onSuccess(BaseModel returnBaseModel) {											
				if (returnBaseModel==null) {
					//
					//
					return;
				}
				if (htmlEditor!=null) {
					htmlEditor.setValue("");
					//htmlEditor.focus();
				}
				Html html = chatTabItem.getHtml();
				if (returnBaseModel.get("message")==null||returnBaseModel.get("message").equals("")) {

				}else {

					html.setHtml(html.getHtml()+"<br>"+returnBaseModel.get("message"));

				}
				chatTabItem.setData("messageIndex", returnBaseModel.get("index"));
				String returnSessionId  = returnBaseModel.get("sessionId");
				if ( chatTabItem.getData("sessionId")==null) {
					chatTabItem.setData("sessionId",returnSessionId);

				}else if (!((String)chatTabItem.getData("sessionId")).equals(returnSessionId)) {
					MessageBox.alert("警告",	"您没有收到与自己会话对应的消息，请联系管理员或者稍后再试！", null);
				}
				
				//MessageBox.alert("警告",	(String)chatTabItem.getData("sessionId"), null);

				//chatTabItem.repaint();
			}
		});
	}

	
	
}
